package com.huang.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huang.common.lang.Result;
import com.huang.entity.Cart;
import com.huang.entity.Commodity;
import com.huang.entity.User;
import com.huang.vo.CartDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author huang
 * @since 2021-09-15
 */
@Api("购物车接口操作")
@RestController
@RequestMapping("/cart")
public class CartController extends BaseController {

    @ApiOperation("查看购物车接口")
    @GetMapping("/list")
    public Result list(Principal principal){

        User user = userService.getByName(principal.getName());

        List<Cart> cartList = cartService.getByUserId(user.getUserId());

        List<CartDto> cartDtoList = new ArrayList<CartDto>();

        cartList.forEach(cart -> {
            CartDto cartDto = new CartDto();
            Commodity commodity = commodityService.getById(cart.getCommodityId());
            cartDto.setId(cart.getId());
            cartDto.setName(commodity.getName());
            cartDto.setPrice(commodity.getPrice());
            cartDto.setShop(commodity.getShop());
            cartDtoList.add(cartDto);
        });

        return Result.succ(cartDtoList);
    }

    @ApiOperation("查看一个购物车接口")
    @GetMapping("/infoo/{commodityId}")
    public Result infoo(@PathVariable("commodityId") Integer commodityId,Principal principal){

        User user = userService.getByName(principal.getName());

        Cart cart = cartService.getOne(new QueryWrapper<Cart>().eq("user_id", user.getUserId()).eq("commodity_id", commodityId));

        return Result.succ(cart);
    }

    @ApiOperation("查看一个购物车软件接口")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Integer id){

        Cart cart = cartService.getById(id);

        Commodity commodity = commodityService.getById(cart.getCommodityId());

        return Result.succ(commodity);
    }


    @ApiOperation("添加到购物车接口")
    @PostMapping("/save/{commodityId}")
    public Result save(@PathVariable("commodityId") Integer commodityId,Principal principal){

        User user = userService.getByName(principal.getName());

        Cart cart = new Cart();

        cart.setUserId(user.getUserId());
        cart.setCommodityId(commodityId);

        cartService.save(cart);

        return Result.succ("已加入购物车");
    }

    @ApiOperation("删除购物车")
    @PostMapping("/delete/{ids}")
    public Result deleteById(@PathVariable("ids") Integer[] ids){

        cartService.removeByIds(Arrays.asList(ids));

        return Result.succ("删除成功");
    }

}
